package com.itheima.health.controller;

import com.google.gson.Gson;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealSrvice;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;


@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {


    @Autowired
    private SetmealSrvice setmealSrvice;

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 套餐的新增
     *
     * @param setmeal
     * @param checkgroupIds
     * @return
     */  // http://localhost:18080/api/setmeal/add?checkgroupIds=10,11,12,13,14,15,16,17
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {

        log.info("[套餐添加数据====>]" + setmeal + "添加的检查项" + checkgroupIds);
        setmealSrvice.addAll(setmeal, checkgroupIds);
        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }


    /**
     * 套餐分页展示
     *
     * @param queryPageBean
     * @return
     */ // http://localhost:18080/api/setmeal/findPage?currentPage=1&pageSize=10&queryString=23
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        log.info("[分页信息]====>" + queryPageBean);

        PageResult page = setmealSrvice.findPage(queryPageBean);

        return new Result(true, MessageConst.ACTION_SUCCESS, page);
    }


    /**
     * 上传到本地服务器
     *
     * @param imgFile
     * @return
     */ // http://localhost:18080/api/setmeal/upload
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile) {
        log.info("[图片上传]，file:{}", imgFile.getOriginalFilename());
        // 获取图片的名称
        String originalFilename = imgFile.getOriginalFilename();
        // 截取图片的 .jqp
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //  为防止图片的覆盖 重新生成图片的名称
        String fileNme = UUID.randomUUID().toString() + substring;

        // 创建一个文件保存基本目录
        File dir = new File(basePath);

        // 判断当前目录是否存在
        if (!dir.exists()) {
            // 若不存在，则创建新的事物
            dir.mkdir();
        }

        try {
            //  将临时文件转存到指定位置
            File newDir = new File(basePath, fileNme);
            imgFile.transferTo(newDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "gJ0laSfCOfoN_f8XuesRNmNCnbGtMuUaphWEywkJ";
        String secretKey = "RZMoY333Ba06heqovzUG6zlTYCsEPNfEidHWbNIX";
        String bucket = "itcast-health-project2";
        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        String localFilePath = basePath+"\\"+fileNme;
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileNme;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        String src ="http://rcs052oxj.hn-bkt.clouddn.com/"+fileNme;
           return new Result(true,MessageConst.UPLOAD_SUCCESS,src);
    }



    }
